<?php


namespace app\index\controller\wanlshop;


use app\common\controller\Wanlshop;
use app\index\model\wanlshop\ActivityGoodsSku;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Package extends Wanlshop
{
    protected $model = null;
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\index\model\wanlshop\Activity;

    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('type','package')
                ->order($sort, $order)
                ->paginate($limit)->each(function ($row){
                    $imageArr = \app\index\model\wanlshop\Goods::where([
                        'id' => ['in',explode(',',$row['goods_ids'])]
                    ])->column('image');
                    $row['images'] = implode(',',$imageArr);
                    $row['rules'] = json_decode($row['rules'],true);
                    return $row;
                });

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $rules = $this->request->post('rules/a');
            $goods_sku = $this->request->post('goods/a');
            if ($params) {
                $result = false;
                Db::startTrans();
                try {

                    $goods_ids = json_decode($params['goods_ids'],true);
                    if(!$goods_ids){
                        $this->error('请选择活动商品');
                    }

                    $params['shop_id'] = $this->shop->id;
                    $params['goods_ids'] = implode(',',$goods_ids);
                    $params['rules'] = json_encode($rules);
                    $result = $this->model->allowField(true)->save($params);
                    $sku = [];
                    $activity_id = $this->model->id;
                    foreach ($goods_sku as $item){
                        $sku[] = [
                            'activity_id' => $activity_id,
                            'sku_id'      => $item['sku_id'],
                            'goods_id'    => $item['goods_id'],
                            'stock'       => $item['stock'],
                            'price'       => 0,
                            'status'       => 'normal',
                        ];
                    }
                    if(empty($sku)){
                        $this->error('请至少选择一个商品');
                    }
                    $activityGoodsSkuModel = new ActivityGoodsSku();
                    $activityGoodsSkuModel->allowField(true)->saveAll($sku);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $rules = $this->request->post('rules/a');
            $goods_sku = $this->request->post('goods/a');
            if ($params) {
                $result = false;
                Db::startTrans();
                try {

                    $goods_ids = json_decode($params['goods_ids'],true);
                    if(!$goods_ids){
                        $this->error('请选择活动商品');
                    }

                    $params['shop_id'] = $this->shop->id;
                    $params['goods_ids'] = implode(',',$goods_ids);
                    $params['rules'] = json_encode($rules);
                    $result = $row->allowField(true)->save($params);
                    $sku = [];
                    $activity_id = $row['id'];
                    foreach ($goods_sku as $item){
                        if($item['id'] == 0){
                            $sku[] = [
                                'activity_id' => $activity_id,
                                'sku_id'      => $item['sku_id'],
                                'goods_id'    => $item['goods_id'],
                                'stock'       => $item['stock'],
                                'price'       => 0,
                                'status'       => 'normal',
                            ];
                        }else{
                            $sku[] = [
                                'id'          => $item['id'],
                                'activity_id' => $activity_id,
                                'sku_id'      => $item['sku_id'],
                                'goods_id'    => $item['goods_id'],
                                'stock'       => $item['stock'],
                                'price'       => 0,
                                'status'       => 'normal',
                            ];
                        }

                    }
                    if(empty($sku)){
                        $this->error('请至少选择一个商品');
                    }
                    $activityGoodsSkuModel = new ActivityGoodsSku();
                    $activityGoodsSkuModel
                        ->whereNotIn('goods_id',$params['goods_ids'])
                        ->where('activity_id',$activity_id)->delete();
                    $activityGoodsSkuModel->allowField(true)->saveAll($sku);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['rules'] = json_decode($row['rules'],true);
        $activityGoodsSkuModel = new ActivityGoodsSku();

        $sku = collection($activityGoodsSkuModel->where([
            'activity_id' => $row['id'],
        ])->select())->toArray();
        $sku = array_column($sku,null,'goods_id');
        $this->assignconfig('goods_ids',explode(',',$row['goods_ids']));
        $this->assignconfig('sku',$sku);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();

            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}